package cn.good.yan.demo2;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 1. Spring Security 正常接口
 * 演示：正常登录：http://localhost:8080/login
 * 输入正确密码，登录成功，
 * 访问：http://localhost:8080/home/info  进入该 getList 方法
 * 得到 当前登录人的用户
 *
 * @author shengren.yan
 * @create 2024-07-15
 */
@RestController
@RequestMapping("/home")
public class homeController {

    // 获取用户信息
    @GetMapping("/info")
    public Map<String, Object> getList() {

        // 存储认证对象的上下文
        SecurityContext context = SecurityContextHolder.getContext();
        // 认证对象
        Authentication authentication = context.getAuthentication();
        // 用户名
        String username = authentication.getName();
        // 身份
        Object principal = authentication.getPrincipal();
        // 凭证(脱敏)
        Object credentials = authentication.getCredentials();
        //权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        System.out.println(username);
        System.out.println(principal);
        System.out.println(credentials);
        System.out.println(authorities);

        //创建结果对象
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", username);
        return result;
    }

}
